/*
 * Thread Demos
 * Spring 2013 TCSS 558
 * Daniel M. Zimmerman
 */

package threads;

/**
 * A class that tests block synchronization, by synchronizing on
 * a shared lock object.
 * 
 * @author Daniel M. Zimmerman
 * @version Spring 2013
 */
public class BlockSync implements Runnable
{
  // Static Fields
  
  /**
   * The default number of threads.
   */
  public static final int DEFAULT_NUMBER_OF_THREADS = 27;
  
  /**
   * An object used as a lock.
   */
  private static final Object LOCK = new Object();
  
  // Instance Fields
  
  /**
   * The number assigned to this BlockSync.
   */
  private final int my_number;

  // Constructor
  
  /**
   * Creates a BlockSync with the specified number assigned.
   * 
   * @param the_number The number.
   */
  public BlockSync(final int the_number)
  { 
    my_number = the_number; 
  }

  // Instance Methods
  
  /**
   * Locks the lock object, prints two lines to standard output, 
   * and then exits.
   */
  public void run()
  {
    for (int i = 0; i < 2; i++)
    {
      synchronized (LOCK)
      {
        System.out.print("I am thread number " + my_number);
        System.out.println();
      }
    }
  }

  // Main Method
  
  /**
   * Creates the number of threads specified at the command line
   * (or 27 threads, if no number is specified at the command line)
   * and runs them.
   * 
   * @param the_args command line arguments; the first is the number of
   * threads to create, all others are ignored.
   */
  public static void main(final String[] the_args)
  {
    int number_of_threads = DEFAULT_NUMBER_OF_THREADS;
    
    if (the_args.length > 0) 
    {
      number_of_threads = Integer.parseInt(the_args[0]);
    }
    
    for (int i = 0; i < number_of_threads; i++)
    {
      final Thread thread = new Thread(new BlockSync(i));
      thread.start();
    }
  }
}
